﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using CoolCode.Linq;

namespace CoolCode.Data
{
    public interface IRepository<T> : IQueryable<T>, IEnumerable<T>, IDisposable
    { 
        void Insert(T entity);
        void Insert(IEnumerable<T> list);

        void Update(T entity);
        //void Update(T entity, T original);
        void Update(IEnumerable<T> list);
		
		 
		/// <summary>
		/// 更新
		/// </summary>  
		/// <param name="predicate">查询条件表达式</param>
		/// <param name="updater">更新表达式</param>
		/// <returns>影响的行数</returns>
		int Update(Expression<Func<T, bool>> predicate, Expression<Func<T, T>> updater);
		 

        void Delete(T entity);
        void Delete(IQueryable<T> query);
        void Delete(IEnumerable<T> list);
        void Delete(Expression<Func<T, bool>> predicate); 
        T Get(Expression<Func<T, bool>> predicate);
		 
    }

    public static class RepositoryExtension
    { 
        public static List<T> List<T>(this IRepository<T> rep) 
        {
            var q = rep ;
            return q.ToList();
        }

        public static List<T> List<T>(this IRepository<T> rep, Expression<Func<T, bool>> predicate) 
        {
            var q = rep.Where(predicate);
            return q.ToList();
        }

        public static bool Contains<T>(this IRepository<T> rep, Expression<Func<T, bool>> predicate)   
        {
            var q = rep.Where(predicate);
            return q.Count() > 0;
        }

        public static void Update<T>(this IRepository<T> rep, Expression<Func<T, bool>> predicate, Action<T> action) 
        {
            var list = rep.List(predicate);
            foreach (T entity in list)
                action(entity);
        }
    } 
}
